<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="店铺" prop="storeId">
              <el-select v-model="queryParams.storeId" placeholder="请选择部门" clearable>
                <el-option v-for="store in storeOptions" :key="store.storeId" :label="store.storeName" :value="store.storeId" />
              </el-select>
            </el-form-item>
            <el-form-item label="销售时间" prop="salesTime">
              <el-date-picker clearable
                v-model="queryParams.salesTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择销售时间"
              />
            </el-form-item>
            <el-form-item label="卡品名称" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入卡品名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:salesData:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="salesDataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="销售ID" align="center" prop="salesId" v-if="false" />
        <el-table-column label="销售时间" align="center" prop="salesTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.salesTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="店铺" align="center" prop="storeName" />
        <el-table-column label="卡品名称" align="center" prop="productName" />
        <el-table-column label="销售数量" align="center" prop="salesQuantity" />
        <el-table-column label="单品佣金" align="center" prop="singleItemCommission" />
        <el-table-column label="佣金" align="center" prop="commissionMoney" />
        <el-table-column label="平台服务费" align="center" prop="platformServiceFee" />
        <el-table-column label="订单发出数" align="center" prop="orderDispatchedNumber" />
        <el-table-column label="激活量" align="center" prop="activationQuantity" />
        <el-table-column label="发货率" align="center" prop="shipmentRate" />
        <el-table-column label="发货激活率" align="center" prop="shipmentActivationRate" />
        <el-table-column label="激活率" align="center" prop="activationRate" />
        <el-table-column label="待发货数量" align="center" prop="shippedQuantity" />
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改销售数据信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="salesDataFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="店铺ID" prop="storeId">
          <el-input v-model="form.storeId" placeholder="请输入店铺ID" />
        </el-form-item>
        <el-form-item label="销售数量" prop="salesQuantity">
          <el-input v-model="form.salesQuantity" placeholder="请输入销售数量" />
        </el-form-item>
        <el-form-item label="销售时间" prop="salesTime">
          <el-date-picker clearable
            v-model="form.salesTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择销售时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="卡品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入卡品名称" />
        </el-form-item>
        <el-form-item label="单品佣金" prop="singleItemCommission">
          <el-input v-model="form.singleItemCommission" placeholder="请输入单品佣金" />
        </el-form-item>
        <el-form-item label="佣金" prop="commissionMoney">
          <el-input v-model="form.commissionMoney" placeholder="请输入佣金" />
        </el-form-item>
        <el-form-item label="平台服务费" prop="platformServiceFee">
          <el-input v-model="form.platformServiceFee" placeholder="请输入平台服务费" />
        </el-form-item>
        <el-form-item label="订单发出数" prop="orderDispatchedNumber">
          <el-input v-model="form.orderDispatchedNumber" placeholder="请输入订单发出数" />
        </el-form-item>
        <el-form-item label="激活量" prop="activationQuantity">
          <el-input v-model="form.activationQuantity" placeholder="请输入激活量" />
        </el-form-item>
        <el-form-item label="发货率" prop="shipmentRate">
          <el-input v-model="form.shipmentRate" placeholder="请输入发货率" />
        </el-form-item>
        <el-form-item label="发货激活率" prop="shipmentActivationRate">
          <el-input v-model="form.shipmentActivationRate" placeholder="请输入发货激活率" />
        </el-form-item>
        <el-form-item label="激活率" prop="activationRate">
          <el-input v-model="form.activationRate" placeholder="请输入激活率" />
        </el-form-item>
        <el-form-item label="待发货数量" prop="shippedQuantity">
          <el-input v-model="form.shippedQuantity" placeholder="请输入待发货数量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SalesData" lang="ts">
import {
  listSalesData,
  getSalesData,
  delSalesData,
  addSalesData,
  updateSalesData,
  getStoreListAll
} from '@/api/company/salesData';
import { SalesDataVO, SalesDataQuery, SalesDataForm } from '@/api/company/salesData/types';
import { StoreVO } from '@/api/company/store/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const salesDataList = ref<SalesDataVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
let storeOptions = ref<StoreVO[]>([]);

const queryFormRef = ref<ElFormInstance>();
const salesDataFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SalesDataForm = {
  salesId: undefined,
  storeId: undefined,
  salesQuantity: undefined,
  salesTime: undefined,
  productName: undefined,
  singleItemCommission: undefined,
  commissionMoney: undefined,
  platformServiceFee: undefined,
  orderDispatchedNumber: undefined,
  activationQuantity: undefined,
  shipmentRate: undefined,
  shipmentActivationRate: undefined,
  activationRate: undefined,
  shippedQuantity: undefined,
  remark: undefined
}
const data = reactive<PageData<SalesDataForm, SalesDataQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeId: undefined,
    salesQuantity: undefined,
    salesTime: undefined,
    productName: undefined,
    singleItemCommission: undefined,
    commissionMoney: undefined,
    platformServiceFee: undefined,
    orderDispatchedNumber: undefined,
    activationQuantity: undefined,
    shipmentRate: undefined,
    shipmentActivationRate: undefined,
    activationRate: undefined,
    shippedQuantity: undefined,
    params: {
    }
  },
  rules: {
    salesId: [
      { required: true, message: "销售ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

const getStoreList = async () => {
  const res = await getStoreListAll();
  storeOptions = res.data;
};

/** 查询销售数据信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSalesData(queryParams.value);
  salesDataList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  salesDataFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: SalesDataVO[]) => {
  ids.value = selection.map(item => item.salesId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加销售数据信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: SalesDataVO) => {
  reset();
  const _salesId = row?.salesId || ids.value[0]
  const res = await getSalesData(_salesId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改销售数据信息";
}

/** 提交按钮 */
const submitForm = () => {
  salesDataFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.salesId) {
        await updateSalesData(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addSalesData(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: SalesDataVO) => {
  const _salesIds = row?.salesId || ids.value;
  await proxy?.$modal.confirm('是否确认删除销售数据信息编号为"' + _salesIds + '"的数据项？').finally(() => loading.value = false);
  await delSalesData(_salesIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('business/salesData/export', {
    ...queryParams.value
  }, `salesData_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  getStoreList();
});
</script>
